package com.yuandm.wxnt;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.yuandm.wxnt.adapter.NewsAdapter;
import com.yuandm.wxnt.bean.NewsData;
import com.yuandm.wxnt.util.DensityUtil;
import com.yuandm.wxnt.util.Sptools;
import com.yuandm.wxnt.util.StringUtil;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class MainActivity extends Activity {
    public ArrayList<NewsData.ListData.NewsList> m_newsData = new ArrayList<NewsData.ListData.NewsList>(3);
    public NewsAdapter m_newsAdapter;
    public ListView lv_list;
    public Gson gson = new Gson();
    public GridView category;
    private Button mLoadMoreBtn;
    private int mCid = 24;
    public String mCatName=null;
    private ProgressDialog progressDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();//初始化界面
        initData(mCid);//初始化数据
        initEvent();//初始化事件
    }

    private void getCategory(){
        String[] categoryArray = getResources().getStringArray(R.array.categories);
        final List<HashMap<String, Category>> categories = new ArrayList<HashMap<String, Category>>();
        for(int i=0;i<categoryArray.length;i++)
        {
            String[] temp = categoryArray[i].split("[|]");
            if (temp.length==2)
            {
                int cid = StringUtil.String2Int(temp[0]);
                String title = temp[1];
                Category type = new Category(cid, title);
                HashMap<String, Category> hashMap = new HashMap<String, Category>();
                hashMap.put("category_title", type);
                categories.add(hashMap);
            }
        }
        CustomSimpleAdapter categoryAdapter = new CustomSimpleAdapter(this, categories, R.layout.category_title,
                new String[]{"category_title"}, new int[]{R.id.category_title});

        category = (GridView)findViewById(R.id.grid01);
        category.setSelector(new ColorDrawable(Color.TRANSPARENT));
        category.setAdapter(categoryAdapter);

        category.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView categoryTitle;
                //恢复每个单元格背景色
                for (int i = 0; i < parent.getChildCount(); i++) {
                    categoryTitle = (TextView) (parent.getChildAt(i));

                    categoryTitle.setBackground(null);
                }
                //设置选择单元格的背景色
                categoryTitle = (TextView) (parent.getChildAt(position));
                categoryTitle.setBackgroundResource(R.drawable.categorybar_item_background);
                //categoryTitle.setBackgroundColor(Color.GRAY);
                categoryTitle.setTextColor(0XFFFFFFFF);
                //获取选中的新闻分类id
                mCid = categories.get(position).get("category_title").getCid();
                mCatName = categories.get(position).get("category_title").getTitle();
                //to open url instead
                if (22 == mCid) {
                    Uri uri = Uri.parse("http://www.yjbg.org/date");
                    startActivity(new Intent(Intent.ACTION_VIEW, uri));
                } else if (23 == mCid) {
                    Uri uri = Uri.parse("http://app.infocio.com");
                    startActivity(new Intent(Intent.ACTION_VIEW, uri));
                } else {
                    m_newsData.clear();
                    initData(mCid);
                }


            }
        });

        final HorizontalScrollView categoryScrollview = (HorizontalScrollView) findViewById(R.id.category_scrollview);
        Button categoryArrowRight = (Button) findViewById(R.id.category_arrow_right);
        categoryArrowRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                categoryScrollview.fling(DensityUtil.px2dip(MainActivity.this, 3000));
            }
        });


    }

    private void initEvent() {
        lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (null == mCatName)
                    mCatName = "热点";
                Intent intent = new Intent(MainActivity.this, NewsDetailsActivity.class);
                intent.putExtra("categoryName", mCatName);
                intent.putExtra("title", m_newsData.get(position).title);
                intent.putExtra("id", m_newsData.get(position).id);
                intent.putExtra("pic", m_newsData.get(position).titlepic);
                intent.putExtra("time", m_newsData.get(position).newspath);
                intent.putExtra("digest", m_newsData.get(position).smalltext);
                intent.putExtra("classId", mCid);
                intent.putExtra("position", position);
                startActivity(intent);

            }
        });
    }

    private void initView() {
        setContentView(R.layout.activity_main);
        ListView lv_list = (ListView)findViewById(R.id.newslist);
        LayoutInflater Inflater = getLayoutInflater();
        View footerView = Inflater.inflate(R.layout.loadmore, null);
        lv_list.addFooterView(footerView);

        getCategory();

        mLoadMoreBtn = (Button)findViewById(R.id.loadmore_btn);
        mLoadMoreBtn.setOnClickListener(loadMoreListener);

        UpdateManager manager = new UpdateManager(MainActivity.this);
        manager.checkUpdate();

        progress("数据加载中", "请稍等......");


    }

    public void initData(int cid) {
        lv_list = (ListView)findViewById(R.id.newslist);
        m_newsAdapter = new NewsAdapter();
        lv_list.setAdapter(m_newsAdapter);
        getNewsFromWeb(0, 20, cid);
    }

    public NewsData parseJson(String jsonData){
        //解析json数据

        NewsData parseData = gson.fromJson(jsonData, NewsData.class);
        return parseData;
    }

    public void getNewsFromWeb(int start_id, int count, int cid) {
        final int innerCid = cid;
        String jsonOldData = Sptools.getString(MainActivity.this, "newslist"+innerCid,"");
        final NewsData newsOldData = parseJson(jsonOldData);

        String path = "http://jrnt.hengzecn.com/Home/Caiji/Show_json?start_id="+start_id+
                "&count="+count+"&cid="+cid;
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(path, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                progressDialog.cancel();
                String jsonData = new String(responseBody);
                NewsData newsData = parseJson(jsonData);
                if(0 == newsData.data.newslist.size()) {
                    Toast toast = Toast.makeText(getApplicationContext(), "没有更多信息了", Toast.LENGTH_LONG);
                    toast.show();
                }
                Sptools.setString(MainActivity.this, "newslist"+innerCid, jsonData);
                processData(newsData);
            }
            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable
                    error)
            {
                progressDialog.cancel();
                processData(newsOldData);
                Toast toast = Toast.makeText(getApplicationContext(), "请检查网络连接", Toast.LENGTH_LONG);
                toast.show();
                error.printStackTrace(System.out);
            }
        });
    }

    public void processData(NewsData newsData) {
        setListViewNews(newsData);
    }

    public void setListViewNews(NewsData newsData) {
        m_newsData.addAll(newsData.data.newslist);
        m_newsAdapter.m_newsData = m_newsData;
        m_newsAdapter.m_mainActivity = MainActivity.this;
        m_newsAdapter.notifyDataSetChanged();
    }

    public void progress(String title,String message){
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.THEME_DEVICE_DEFAULT_DARK);
        progressDialog.setMessage(message);
        progressDialog.setTitle(title);

        progressDialog.setMax(100);
        progressDialog.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK )
        {
            // 创建退出对话框
            AlertDialog isExit = new AlertDialog.Builder(this).create();
            // 设置对话框标题
            isExit.setTitle("系统提示");
            // 设置对话框消息
            isExit.setMessage("确定要退出吗");
            // 添加选择按钮并注册监听
            isExit.setButton("确定", listener);
            isExit.setButton2("取消", listener);
            // 显示对话框
            isExit.show();

        }

        return false;

    }
    /**监听对话框里面的button点击事件*/
    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dialog, int which)
        {
            switch (which)
            {
                case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
                    finish();
                    break;
                case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
                    break;
                default:
                    break;
            }
        }
    };


    private OnClickListener loadMoreListener = new OnClickListener() {
        @Override
        public void onClick(View v)
        {
            getNewsFromWeb(m_newsData.size(), 20, mCid);
        }
    };
}